package com.hanson.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.Const;
import com.hanson.common.bean.SkillTimeBean;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.SeckillGoodsBean;
import com.hanson.mapper.SeckillGoodsBeanMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.text.ParseException;
import java.util.*;

@Slf4j
@Service
public class SeckillGoodsService {
    @Autowired
    private SeckillGoodsBeanMapper seckillGoodsBeanMapper;

    public void add(SeckillGoodsBean seckillGoodsBean) throws Exception {
        if (null == seckillGoodsBean.getGoodsId()) {
            throw new BusinessException("商品ID不能为空");
        }
        List<SeckillGoodsBean> seckillGoodsBeanList = seckillGoodsBeanMapper.selectByGoodsId(seckillGoodsBean.getGoodsId());
        if(CollectionUtils.isNotEmpty(seckillGoodsBeanList)){
            throw new BusinessException("当前商品已在秒杀中，不能重复添加");
        }
        seckillGoodsBean.setCreateDate(new Date());
        seckillGoodsBean.setStatus(0);
        seckillGoodsBean.setIsShow(1);
        seckillGoodsBean.setGoodsPrice(BusinessUtil.getDbAmount(seckillGoodsBean.getWebGoodsPrice()));
        seckillGoodsBean.setSeckillPrice(BusinessUtil.getDbAmount(seckillGoodsBean.getWebSeckillPrice()));
        seckillGoodsBeanMapper.insert(seckillGoodsBean);
    }

    public void modify(SeckillGoodsBean seckillGoodsBean) throws Exception {
        if (null == seckillGoodsBean.getGoodsId()) {
            throw new BusinessException("商品ID不能为空");
        }
        SeckillGoodsBean returnBean = seckillGoodsBeanMapper.selectByPrimaryKey(seckillGoodsBean.getId());
        if (null != returnBean) {
            List<SeckillGoodsBean> seckillGoodsBeanList = seckillGoodsBeanMapper.selectByGoodsId(seckillGoodsBean.getGoodsId());
            if(CollectionUtils.isNotEmpty(seckillGoodsBeanList) && !seckillGoodsBeanList.get(0).getGoodsId().equals(returnBean.getGoodsId())){
                throw new BusinessException("当前商品已在秒杀中，不能重复添加");
            }
            seckillGoodsBean.setUpdateDate(new Date());
            seckillGoodsBean.setCreateDate(returnBean.getCreateDate());
            seckillGoodsBean.setIsShow(returnBean.getIsShow());
            seckillGoodsBean.setStatus(returnBean.getStatus());
            seckillGoodsBean.setGoodsPrice(BusinessUtil.getDbAmount(seckillGoodsBean.getWebGoodsPrice()));
            seckillGoodsBean.setSeckillPrice(BusinessUtil.getDbAmount(seckillGoodsBean.getWebSeckillPrice()));
            seckillGoodsBeanMapper.updateByPrimaryKey(seckillGoodsBean);
        }
    }

    public SeckillGoodsBean selectById(Integer id) {
        SeckillGoodsBean seckillGoodsBean = seckillGoodsBeanMapper.selectByPrimaryKey(id);
        if (null != seckillGoodsBean) {
            seckillGoodsBean.setWebGoodsPrice(BusinessUtil.getWebAmount(seckillGoodsBean.getGoodsPrice()));
            seckillGoodsBean.setWebSeckillPrice(BusinessUtil.getWebAmount(seckillGoodsBean.getSeckillPrice()));
        }
        return seckillGoodsBean;
    }

    public void deleteById(Integer id) {
        seckillGoodsBeanMapper.deleteByPrimaryKey(id);
    }

    public Page<SeckillGoodsBean> listSeckillGoods(Page<SeckillGoodsBean> page, SeckillGoodsBean seckillGoodsBean) {
        List<SeckillGoodsBean> list = seckillGoodsBeanMapper.listSeckillGoods(page, seckillGoodsBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                c.setWebGoodsPrice(BusinessUtil.getWebAmount(c.getGoodsPrice()));
                c.setWebSeckillPrice(BusinessUtil.getWebAmount(c.getSeckillPrice()));
            });
        }
        return page.setRecords(list);
    }

    public void updateIsShow(int isShow, int id) {
        seckillGoodsBeanMapper.updateIsShow(isShow, id);
    }

    public long getSurplusSecond() throws ParseException {
        Map<Integer, SkillTimeBean> skillTimeMap = Const.SKILL_TIME;
        List<SkillTimeBean> list = new ArrayList<>();
        skillTimeMap.entrySet().stream().forEach(c -> {
            SkillTimeBean skillTimeBean = c.getValue();
            list.add(skillTimeBean);
        });
        String currentDay = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        String tomorrowDay = DateFormatUtils.format(DateUtils.addDays(new Date(), 1), "yyyy-MM-dd");
        int nowTime = Integer.parseInt(DateFormatUtils.format(new Date(), "HH"));
        int firstTime = Integer.parseInt(list.get(0).getTime().split(":")[0]);
        String activeTime = null;
        for (int i = 0; i < list.size(); i++) {
            int time = Integer.parseInt(list.get(i).getTime().split(":")[0]);
            if (i == list.size() - 1) {
                if (nowTime >= time || nowTime < firstTime) {
                    if (nowTime >= time) {
                        activeTime = tomorrowDay + " " + list.get(0).getTime();
                    } else {
                        activeTime = currentDay + " " + list.get(0).getTime();
                    }
                    break;
                }
            } else {
                int nextTime = Integer.parseInt(list.get(i + 1).getTime().split(":")[0]);
                if (nowTime >= time && nowTime < nextTime) {
                    activeTime = currentDay + " " + list.get(i + 1).getTime();
                    break;
                }
            }
        }
        long diffTime = DateUtils.parseDate(activeTime, "yyyy-MM-dd HH:mm").getTime() - System.currentTimeMillis();
        return diffTime / 1000;
    }

    public List<SkillTimeBean> getSkillTimeData(ModelMap modelMap) {
        List<SeckillGoodsBean> seckillGoodsBeanList = seckillGoodsBeanMapper.selectCurrentTimeData();
        Map<Integer, List<SeckillGoodsBean>> dataMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(seckillGoodsBeanList)) {
            seckillGoodsBeanList.stream().forEach(c -> {
                c.setWebGoodsPrice(BusinessUtil.getWebAmount(c.getGoodsPrice()));
                c.setWebSeckillPrice(BusinessUtil.getWebAmount(c.getSeckillPrice()));
                c.setUsableNum(c.getStock() - c.getSales());
                c.setPercent(BusinessUtil.getPercent(c.getStock() - c.getSales(), c.getStock()));
                if (dataMap.containsKey(c.getTimeType())) {
                    dataMap.get(c.getTimeType()).add(c);
                } else {
                    List<SeckillGoodsBean> list = new ArrayList<>();
                    list.add(c);
                    dataMap.put(c.getTimeType(), list);
                }
            });
        }

        Map<Integer, SkillTimeBean> skillTimeMap = Const.SKILL_TIME;
        List<SkillTimeBean> list = new ArrayList<>();
        skillTimeMap.entrySet().stream().forEach(c -> {
            SkillTimeBean skillTimeBean = c.getValue();
            skillTimeBean.getSeckillGoodsBeanList().clear();;
            list.add(skillTimeBean);
        });
        int nowTime = Integer.parseInt(DateFormatUtils.format(new Date(), "HH"));
        int firstTime = Integer.parseInt(list.get(0).getTime().split(":")[0]);
        for (int i = 0; i < list.size(); i++) {
            int time = Integer.parseInt(list.get(i).getTime().split(":")[0]);
            if (i == list.size() - 1) {
                if (nowTime < time && nowTime > firstTime) {
                    list.get(i).setStatus(0);
                    list.get(i).setStatusName("即将开始");
                } else if (nowTime >= time || nowTime < firstTime) {
                    list.get(i).setStatus(1);
                    list.get(i).setStatusName("抢购中");
                    modelMap.put("currentIndex",i);
                } else if (nowTime >= firstTime && nowTime < time) {
                    list.get(i).setStatus(2);
                    list.get(i).setStatusName("已结束");
                }
            } else {
                int nextTime = Integer.parseInt(list.get(i + 1).getTime().split(":")[0]);
                if (nowTime >= time && nowTime < nextTime) {
                    list.get(i).setStatus(1);
                    list.get(i).setStatusName("抢购中");
                    modelMap.put("currentIndex",i);
                } else if (nowTime < time) {
                    list.get(i).setStatus(0);
                    list.get(i).setStatusName("即将开始");
                } else if (nowTime >= nextTime) {
                    list.get(i).setStatus(2);
                    list.get(i).setStatusName("已结束");
                }
            }
            if (dataMap.containsKey(list.get(i).getId())) {
                list.get(i).getSeckillGoodsBeanList().addAll(dataMap.get(list.get(i).getId()));
            }
        }
        return list;
    }
}
